package org.jeecg.modules.travel.user.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.jeecg.modules.travel.user.entity.TravelWechatUser;
import org.jeecg.modules.travel.user.entity.TravelDrivers;
import org.jeecg.modules.travel.user.entity.TravelStudents;
import org.jeecg.modules.travel.user.mapper.TravelWechatUserMapper;
import org.jeecg.modules.travel.user.mapper.TravelDriversMapper;
import org.jeecg.modules.travel.user.mapper.TravelStudentsMapper;
import org.jeecg.modules.travel.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.apache.commons.beanutils.converters.DateConverter;
import org.jeecg.common.api.vo.Result;


import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;


import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.base.service.BaseCommonService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @Description: jeecg 测试demo
 * @Author: jeecg-boot
 * @Date:  2018-12-29
 * @Version: V1.0
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<TravelWechatUserMapper, TravelWechatUser> implements IUserService {
	@Autowired
	TravelDriversMapper TDMapper;
	@Autowired
	TravelStudentsMapper TSMapper;
	@Autowired
	TravelWechatUserMapper TWUMapper;
	@Autowired
	ISysUserService sysUserService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private RedisUtil redisUtil;

    
    @Override
    public TravelWechatUser queryById(String openId) {
        return TWUMapper.queryById(openId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertUser(JSONObject user) {
        // 查询用户是否存在
        TravelWechatUser ui = TWUMapper.queryById(user.getString("openId"));
        if( ui != null ){
            // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 1;
        }

        //创建系统用户
        SysUser suser = new SysUser();
		try {

            // 检查phone是否已经注册
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
            queryWrapper.eq("phone", user.getString("phone"));
            List<SysUser> userList = sysUserService.list(queryWrapper);
            if(userList.size() > 0){
                return 3;
            }
            suser.setUsername(user.getString("name") + oConvertUtils.randomGen(6) );
            suser.setPhone(user.getString("phone"));
            suser.setRealname(user.getString("nickName"));
            suser.setAvatar(user.getString("avatarUrl"));
			suser.setSex(user.getInteger("gender"));//设置创建时间
			suser.setWorkNo(user.getString("openId"));//设置创建时间
            suser.setActivitiSync(0);
			suser.setCreateTime(new Date());//设置创建时间
			String salt = oConvertUtils.randomGen(8);
			suser.setSalt(salt);
			String passwordEncode = PasswordUtil.encrypt(suser.getUsername(), oConvertUtils.randomGen(32), salt);
			suser.setPassword(passwordEncode);
			suser.setStatus(1);
			suser.setDelFlag(CommonConstant.DEL_FLAG_0);
			//用户表字段org_code不能在这里设置他的值
            suser.setOrgCode(null);
			// 保存用户走一个service 保证事务
            //获取租户ids
            String selectedRoles = "";
            String selectedDeparts = "";
            String relTenantIds = "";
            sysUserService.saveUser(suser, selectedRoles, selectedDeparts, relTenantIds);
            baseCommonService.addLog("拼车系统用户注册，username： " +suser.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
		} catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 2;
		}

        // 创建用户
        ui = new TravelWechatUser();
        ui.setSysUid(suser.getId());
        ui.setAvatarUrl(user.getString("avatarUrl"));
        ui.setGender(user.getInteger("gender"));
        ui.setName(user.getString("name"));
        ui.setPhone(user.getString("phone"));
        ui.setNickName(user.getString("nickName"));
        ui.setOpenId(user.getString("openId"));
        ui.setTeacher(user.getInteger("teacher"));
        TWUMapper.insert(ui);

        //创建司机信息
        JSONObject driver_info = user.getJSONObject("driver_info");
        if( driver_info != null){
            TravelDrivers di = new TravelDrivers();
            di.setUid(suser.getId());
            di.setLicense(driver_info.getString("license"));
            di.setSeating(driver_info.getInteger("seating"));
            di.setType(driver_info.getString("type"));
            TDMapper.insert(di);
        }

        //创建学生信息
        JSONArray student = user.getJSONArray("student");
        if( student != null ){
            for (int i = 0; i < student.size() ; i++) {
                JSONObject si = student.getJSONObject(i);
                TravelStudents ts = new TravelStudents();
                if(ts != null){
                    ts.setClassName(si.getString("class"));
                    ts.setName(si.getString("name"));
                    ts.setSchool(si.getString("school"));
                    ts.setStudentid(si.getString("studentid"));
                    ts.setUid(suser.getId());
                    TSMapper.insert(ts);
                }
            }
        }
        return 0;
    }

    @Override
    public boolean updateUser(JSONObject user) {
        // TWUMapper.updateUser(user);
        return true;
    }

    @Override
    public Result<JSONObject> Login(String OpenId) {
        Result<JSONObject> obj = new Result<JSONObject>();
        // 查询用户是否存在
        TravelWechatUser ui = TWUMapper.queryById(OpenId);
        if( ui == null ){
            obj.setSuccess(false);
            obj.setMessage("用户未注册");
            return obj;
        }
        SysUser sysUser = sysUserService.getById(ui.getSysUid());
        if( sysUser == null ){
            obj.setSuccess(false);
            obj.setMessage("查找用户失败");
            return obj;
        }
		String username = sysUser.getUsername();
		String syspassword = sysUser.getPassword();

        JSONObject info = new JSONObject();

		// 生成token
		String token = JwtUtil.sign(username, syspassword);
        
		// 设置token缓存有效时间
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);


		// token放到返回值
        info.put("token", token);

        // 用户信息放入返回值
        info.put("uid", sysUser.getId());
        info.put("name", ui.getName());
        info.put("phone", ui.getPhone());
        info.put("nick_name", ui.getNickName());
        info.put("avatar_url", ui.getAvatarUrl());
        info.put("gender", ui.getGender());
        info.put("teacher", ui.getTeacher());

        //获取司机信息
        QueryWrapper<TravelDrivers>  tdq = new QueryWrapper<TravelDrivers>();;
        tdq.eq("uid", ui.getId());
        TravelDrivers tdi = TDMapper.selectOne(tdq);
        info.put("driver_info", tdi);

        //获取学生信息
        QueryWrapper<TravelStudents>  tsq = new QueryWrapper<TravelStudents>();;
        tsq.eq("uid", ui.getSysUid());
        List<TravelStudents> tsli = TSMapper.selectList(tsq);
        info.put("student", tsli);

        obj.setSuccess(true);
        obj.setMessage("登录成功");
        obj.setResult(info);
        return obj;
    }

}








